<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="管家账号" prop="accountId" v-if="false">
              <el-input v-model="queryParams.accountId" placeholder="请输入管家账号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="广告主账号" prop="advertiserId">
              <el-input v-model="queryParams.advertiserId" placeholder="请输入广告主账号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="投手名" prop="createName">
              <el-input v-model="queryParams.createName" placeholder="请输入投手名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="短剧名" prop="dramaTitle">
              <el-input v-model="queryParams.dramaTitle" placeholder="请输入短剧名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建项目完整json" prop="projectJson"  v-if="false">
              <el-input v-model="queryParams.projectJson" placeholder="请输入创建项目完整json" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="提交项目数量" prop="projectNum"  v-if="false">
              <el-input v-model="queryParams.projectNum" placeholder="请输入提交项目数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="提交广告数量" prop="promotionNum"  v-if="false">
              <el-input v-model="queryParams.promotionNum" placeholder="请输入提交广告数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="提交项目、广告json" prop="projectPromotionJson"  v-if="false">
              <el-input v-model="queryParams.projectPromotionJson" placeholder="请输入提交项目、广告json" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="定时发布时间" prop="pushTime">
              <el-date-picker clearable v-model="queryParams.pushTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择定时发布时间" />
            </el-form-item>
            <el-form-item label="成功数量" prop="successNum"  v-if="false">
              <el-input v-model="queryParams.successNum" placeholder="请输入成功数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="失败数量" prop="failNum"  v-if="false">
              <el-input v-model="queryParams.failNum" placeholder="请输入失败数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:templateTask:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:templateTask:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:templateTask:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:templateTask:export']">导出</el-button>
          </el-col>
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">{{ appStore.accountName || '未设置' }}</div>
          </div>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="templateTaskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务id" align="center" prop="taskId" v-if="false" />
        <el-table-column label="管家账号" align="center" prop="accountId" v-if="false" />
        <el-table-column label="广告主账号" align="center" prop="advertiserId" />
        <el-table-column label="投手名" align="center" prop="createName" />
        <el-table-column label="任务名称" align="center" prop="name" />
        <el-table-column label="短剧名" align="center" prop="dramaTitle" />
        <el-table-column label="广告类型" align="center" prop="promotionType" />
        <!-- <el-table-column label="创建项目完整json" align="center" prop="projectJson" /> -->
        <el-table-column label="提交项目数量" align="center" prop="projectNum" />
        <el-table-column label="提交广告数量" align="center" prop="promotionNum" />
        <!-- <el-table-column label="提交项目、广告json" align="center" prop="projectPromotionJson" /> -->
        <el-table-column label="执行状态" align="center" prop="executeStatus">
          <template #default="scope">
            <el-tag :type="scope.row.executeStatus == 0 ? 'danger' : 'success'">{{ scope.row.executeStatus == 0 ? '未提交' : '提交完成' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交类型" align="center" prop="submitType">
          <template #default="scope">
            <el-tag v-if="scope.row.submitType == 0">立即提交</el-tag>
            <el-tag v-if="scope.row.submitType == 1">异步提交</el-tag>
            <el-tag v-if="scope.row.submitType == 2">定时提交</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="定时发布时间" align="center" prop="pushTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.pushTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成功数量" align="center" prop="successNum" />
        <el-table-column label="失败数量" align="center" prop="failNum" />
        <el-table-column label="备注描述" align="center" prop="remark" width="180" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="复制" placement="top">
              <el-button link type="primary" icon="DocumentCopy" @click="handleCopy(scope.row)" v-hasPermi="['oce:templateTask:copy']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oce:templateTask:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oce:templateTask:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改巨量项目广告任务记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="templateTaskFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="管家账号" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入管家账号" />
        </el-form-item>
        <el-form-item label="广告主账号" prop="advertiserId">
          <el-input v-model="form.advertiserId" placeholder="请输入广告主账号" />
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="创建项目完整json" prop="projectJson">
          <el-input v-model="form.projectJson" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="提交项目数量" prop="projectNum">
          <el-input v-model="form.projectNum" placeholder="请输入提交项目数量" />
        </el-form-item>
        <el-form-item label="提交广告数量" prop="promotionNum">
          <el-input v-model="form.promotionNum" placeholder="请输入提交广告数量" />
        </el-form-item>
        <el-form-item label="提交项目、广告json" prop="projectPromotionJson">
          <el-input v-model="form.projectPromotionJson" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="定时发布时间" prop="pushTime">
          <el-date-picker clearable v-model="form.pushTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择定时发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="成功数量" prop="successNum">
          <el-input v-model="form.successNum" placeholder="请输入成功数量" />
        </el-form-item>
        <el-form-item label="失败数量" prop="failNum">
          <el-input v-model="form.failNum" placeholder="请输入失败数量" />
        </el-form-item>
        <el-form-item label="备注描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TemplateTask" lang="ts">
import { listTemplateTask, getTemplateTask, delTemplateTask, addTemplateTask, updateTemplateTask } from '@/api/advertisement/templateTask';
import { TemplateTaskVO, TemplateTaskQuery, TemplateTaskForm } from '@/api/advertisement/templateTask/types';
import { useAppStore } from '@/store/modules/app';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();
const router = useRouter();

const templateTaskList = ref<TemplateTaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const templateTaskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TemplateTaskForm = {
  taskId: undefined,
  accountId: undefined,
  advertiserId: undefined,
  name: undefined,
  projectJson: undefined,
  projectNum: undefined,
  promotionNum: undefined,
  projectPromotionJson: undefined,
  executeStatus: undefined,
  submitType: undefined,
  pushTime: undefined,
  successNum: undefined,
  failNum: undefined,
  remark: undefined
};
const data = reactive<PageData<TemplateTaskForm, TemplateTaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: undefined,
    name: undefined,
    projectJson: undefined,
    projectNum: undefined,
    promotionNum: undefined,
    projectPromotionJson: undefined,
    executeStatus: undefined,
    submitType: undefined,
    pushTime: undefined,
    successNum: undefined,
    failNum: undefined,
    createName: undefined,
    dramaTitle: undefined,
    params: {}
  },
  rules: {
    taskId: [{ required: true, message: '任务id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询巨量项目广告任务记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTemplateTask(queryParams.value);
  templateTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  templateTaskFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TemplateTaskVO[]) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加巨量项目广告任务记录';
};
// 复制
const handleCopy = async (row?: TemplateTaskVO) => {
  router.push({ path: 'batchadd', query: { taskId: row.taskId } });
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TemplateTaskVO) => {
  reset();
  const _taskId = row?.taskId || ids.value[0];
  const res = await getTemplateTask(_taskId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改巨量项目广告任务记录';
};

/** 提交按钮 */
const submitForm = () => {
  templateTaskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.taskId) {
        await updateTemplateTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTemplateTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TemplateTaskVO) => {
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除巨量项目广告任务记录编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await delTemplateTask(_taskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oce/templateTask/export',
    {
      ...queryParams.value
    },
    `templateTask_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
